package com.gzx.spring.mq.service;

import java.io.IOException;
import java.util.Date;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.gzx.spring.mq.pojo.RiskOpMsg;
import com.rabbitmq.client.Channel;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import java.util.Random;

@Service
@Slf4j
public class RiskMqService {
	@Resource
	private RabbitTemplate rabbitTemplate;

	public void send(RiskOpMsg riskOpMsg) {
		Random random = new Random();
		String num = String.format("%03d", random.nextInt(999));
		String time = DateUtils.format(new Date(), "yyyyMMddHHmmss");
		riskOpMsg.setId("MQ-" + time + "-" + num);
		String message = JSONObject.toJSONString(riskOpMsg);
		String exchange = "risk"; // 交换机名
		String routingKey = "risk-str"; // 路由键
		rabbitTemplate.convertAndSend(exchange, routingKey, message);
	}

	@RabbitListener(queues = "risk-str-self")
	public void handleMessageTest(String message, Channel channel, Message msg) {
		RiskOpMsg riskOpMsg = JSONObject.parseObject(message, RiskOpMsg.class);
		log.info("用于验证联通性 id:{},type:{},note:{}", riskOpMsg.getId(), riskOpMsg.getMsgType(), riskOpMsg.getNote());
		try {
			long deliveryTag = msg.getMessageProperties().getDeliveryTag();
			channel.basicAck(deliveryTag, false);
		} catch (IOException e) {
			log.error("error", e);
		}
	}
}
